#include "Table.H"
#include <unistd.h>
#include "Deck.H"
unsigned const int DEAL_SIZE=4 ;

void Table::AddLooseCard ( std::vector<Card*> *list )
{
	for ( UINT16 i=0; i< list->size(); i++ )
	{
		mLooseCards.push_back( list->at(i) );
	}
}
Table::Table( int numHouse ):mNumHouses( numHouse ),mCurrentPlayer(NULL),mStartPlayer(NULL) 
{
	mDeck = new Deck();
}

void Table::RegisterPlayer(Player *p)
{
	mPlayers.push_back( p );
	p->SetMyTable(this);
}

void Table::Start( Player *firstPlayer)
{
	mCurrentPlayer = mStartPlayer = firstPlayer;
	FreshDeal();

	Run();
}

void Table::ProcessEventQueue() 
{
	Event *e = mEventQueue.back();
	mEventQueue.pop_back();
	std::cout << " #TableEvent" << std::endl;
	switch ( e->What() )
	{

		case ep_HOUSE_INFO      :
		case ep_LOOSE_THROW     :
		case ep_HOUSE_BUILD	    :
		case ep_HOUSE_LOOSE_ADD :
		case ep_HOUSE_ADD       :  
		case ep_HOUSE_ADDFLOORS :
		case ep_PICK            :
		case ep_DEAL_AGAIN      : { FreshDeal(); break; }
		default: break;

	}

	mCurrentPlayer = mCurrentPlayer->GetNextPlayer();
};

void Table::FreshDeal()
{
	Event *e = new Event( ep_DEAL_AGAIN ); //please clean up your shit.
	NotifyAll( e ); // Don't suffle before cleanup is done.
	std::vector<Card*> cards; 
	bool color_found = false;
	do 
	{
		std::cout << "******Deal Again****** ";
		while ( cards.size() )
		{
			delete cards.back();
			cards.pop_back();
		}
		mDeck->Suffle();
	
		mDeck->Deal( DEAL_SIZE , &cards );
		std::cout << "\ndeal rank: " ;
		for ( UINT16 i=0; i < cards.size(); i++)
		{
			std::cout << cards.at(i)->GetRank() << ", " ;
			//if ( cards.at(i)->GetRank() >= 9 ) { break; }
		}
		for ( UINT16 i=0; i < cards.size(); i++)
		{
			if ( cards.at(i)->GetRank() >= 9 ) { color_found=true;  std::cout << "\nDeal DONE\n" ; break; }
		}
	}while( !color_found );
	mStartPlayer->Notify( new Event( et_TAKE_FROM_DECK, 0, 0, 0, &cards ));
	cards.clear(); // dont delete any cards.
	mDeck->Deal( DEAL_SIZE , &cards );
	AddLooseCard( &cards );
	mStartPlayer->Notify( new Event( et_GIVE_FLOORS ));
	e = new Event( eALL_UPDATE, 0, 0, 0, &cards );
	NotifyAll(e);
}

void Table::NotifyAll( Event *e )
{
	Event *evt=NULL;
	for ( UINT16 i=0; i < mPlayers.size(); i++ )
	{
		std::cout << "Sending Event " << *e << ", size" << mPlayers.size();
		evt = new Event(e);//Post new event
		mPlayers.at(i)->Notify(evt);
	}
	delete e;

}
